const app = getApp()
const { get, del } = require('../../utils/request')

Page({
  data: {
    posts: [],
    page: 1,
    limit: 10,
    hasMore: true,
    isLoading: false
  },

  onLoad() {
    this.loadPosts()
  },

  async loadPosts(showLoading = true) {
    if (this.data.isLoading) return
    
    try {
      if (showLoading) {
        wx.showLoading({ title: '加载中' })
      }
      
      this.setData({ isLoading: true })
      
      const res = await get('/community/my-posts', {
        page: this.data.page,
        limit: this.data.limit
      })
      
      if (res.code === 0) {
        // 格式化时间
        const formattedPosts = res.data.posts.map(post => ({
          ...post,
          createdAt: this.formatTime(new Date(post.createdAt))
        }))
        
        this.setData({
          posts: this.data.page === 1 ? formattedPosts : [...this.data.posts, ...formattedPosts],
          hasMore: formattedPosts.length === this.data.limit
        })
      } else {
        throw new Error(res.message)
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    } finally {
      if (showLoading) {
        wx.hideLoading()
      }
      this.setData({ isLoading: false })
    }
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.setData({
        page: this.data.page + 1
      }, () => {
        this.loadPosts(false)
      })
    }
  },

  // 查看帖子详情
  viewPostDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/community/detail?id=${id}`
    })
  },

  // 编辑帖子
  editPost(e) {
    const post = e.currentTarget.dataset.post
    wx.navigateTo({
      url: `/pages/community/edit?id=${post.id}`
    })
  },

  // 删除帖子
  deletePost(e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要删除这条帖子吗？',
      success: (res) => {
        if (res.confirm) {
          this.handleDelete(id)
        }
      }
    })
  },

  // 处理删除操作
  async handleDelete(id) {
    try {
      wx.showLoading({ title: '删除中' })
      
      const res = await del(`/community/posts/${id}`)
      
      if (res.code === 0) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        // 更新列表，移除已删除的帖子
        this.setData({
          posts: this.data.posts.filter(post => post.id !== id)
        })
      } else {
        throw new Error(res.message)
      }
    } catch (error) {
      wx.showToast({
        title: '请先删除对应的菜谱',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 预览图片
  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      urls,
      current
    })
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true
    }, async () => {
      await this.loadPosts(false)
      wx.stopPullDownRefresh()
    })
  },

  // 触底加载更多
  onReachBottom() {
    this.loadMore()
  }
}) 